package util

import (
	"crypto/md5"
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
)

//生成32位md5字串
func GetMd5String(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

//生成Guid字串
func UniqueId() string {
	b := make([]byte, 48)

	if _, err := io.ReadFull(rand.Reader, b); err != nil {
		return ""
	}
	return GetMd5String(base64.URLEncoding.EncodeToString(b))
}

func StructToJson(v interface{}) string {

	data, err := json.Marshal(v)

	if err != nil {
		fmt.Println(err)
		return ""
	}

	return string(data)
}

func JsonToStruct(str string, object interface{}) error {

	if str == "" {
		return errors.New("str is empty")
	}

	json.Unmarshal([]byte(str), object)

	return nil
}
func ByteToStruct(data []byte, object interface{}) error {

	err := json.Unmarshal(data, object)

	return err
}
